package com.cxf.dao.impl;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.cxf.dao.db.PetStoreDao;
import com.cxf.entity.Pet;
import com.cxf.entity.PetStore;
import com.cxf.method.DMethod;

public class PetStoreDaoImpl implements PetStoreDao {
	
	public PetStore findPetStoreByName(String name) {
		String str = "select * from petstore where name=?";
		ArrayList<Object> list = new ArrayList<Object>();
		list.add(name);
		PetStore petStore = new PetStore();
		ResultSet resultSet = DMethod.look(str, list);
		try {
			while(resultSet.next()) {
				petStore.setBalance(resultSet.getFloat("balance"));
				petStore.setStoreId(resultSet.getInt("id"));
				petStore.setStoreName(resultSet.getString("name"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return petStore;
	}
	@Override
	public void keepPet(Pet pet) {
		String str = "insert into pet(name,typeName,health,love,birthday,price) values(?,?,?,?,?,?)";
		ArrayList< Object> list = new ArrayList<Object>();
		list.add(pet.getName());
		list.add(pet.getTypeName());
		list.add(pet.getHealth());
		list.add(pet.getLove());
		list.add(pet.getBirthday());
		list.add(pet.getPrice());
		DMethod.update(str, list);
		
	}

	@Override
	public float getBalance(int i) {
		String str = "select balance from petstore where id=?";
		ResultSet resultSet = null;
		ArrayList<Object> list = new ArrayList<Object>();
		list.add(i);
		resultSet = DMethod.look(str, list);
		float balance = 0;
		try {
			while (resultSet.next()) {
				balance = resultSet.getFloat("balance");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return balance;
	}

	@Override
	public int updateBalance(PetStore petStore) {
		ArrayList<Object> list = new ArrayList<Object>();
		String str = "update petstore set balance=? where id=?";
		list.add(petStore.getBalance());
		list.add(petStore.getStoreId());
		int res = DMethod.update(str, list);	
		return res;
	}

	
	@Override
	public boolean identity(String user, String password) {
		boolean flag = false;
		String str = "select password from petstore where name=?";
		ArrayList<Object> list = new ArrayList<Object>();
		list.add(user);
		String password1 = null;
		String password2 = null;
		ResultSet res = DMethod.look(str, list);
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");        
	        md.update(password.getBytes());
	        password1 = new BigInteger(1, md.digest()).toString(16);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
		try {
			while (res.next()) {
				password2 = res.getString("password");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (password1.equals(password2)) {
			flag = true;
		} else {
			flag = false;
		}
		return flag;
	}
}
